<?php

require_once __DIR__.'/vendor/autoload.php';

// 加载环境变量
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// 创建数据库连接
try {
    $pdo = new PDO(
        "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_DATABASE']};charset=utf8mb4",
        $_ENV['DB_USERNAME'],
        $_ENV['DB_PASSWORD'],
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );

    echo "✅ 数据库连接成功\n";

    // 获取admin用户
    $userResult = $pdo->query("SELECT id, username FROM users WHERE username = 'admin'");
    $user = $userResult->fetch();

    if (!$user) {
        echo "❌ 未找到admin用户，请先运行 create_admin_user.php\n";
        exit(1);
    }

    echo "✅ 找到用户: {$user['username']} (ID: {$user['id']})\n";

    // 获取超级管理员角色
    $roleResult = $pdo->query("SELECT id, name FROM roles WHERE code = 'super_admin'");
    $role = $roleResult->fetch();

    if (!$role) {
        echo "❌ 未找到超级管理员角色\n";
        exit(1);
    }

    echo "✅ 找到角色: {$role['name']} (ID: {$role['id']})\n";

    // 检查是否已经存在关联
    $existingResult = $pdo->prepare("
        SELECT COUNT(*) as count FROM user_roles
        WHERE user_id = ? AND role_id = ?
    ");
    $existingResult->execute([$user['id'], $role['id']]);
    $existing = $existingResult->fetch();

    if ($existing['count'] > 0) {
        echo "ℹ️ 用户角色关联已存在\n";
    } else {
        // 创建用户角色关联 - 包含所有必需字段
        $stmt = $pdo->prepare("
            INSERT INTO user_roles (
                user_id, role_id, start_date, status, assigned_by, assigned_at, reason, created_at, updated_at
            ) VALUES (?, ?, CURDATE(), 'active', 1, NOW(), '系统自动分配', NOW(), NOW())
        ");
        $stmt->execute([$user['id'], $role['id']]);
        echo "✅ 成功为用户 '{$user['username']}' 分配角色 '{$role['name']}'\n";
    }

    // 验证关联结果
    $verifyResult = $pdo->query("
        SELECT u.username, r.name as role_name, r.code as role_code
        FROM users u
        JOIN user_roles ur ON u.id = ur.user_id
        JOIN roles r ON ur.role_id = r.id
        WHERE u.username = 'admin'
    ");
    $verification = $verifyResult->fetch();

    if ($verification) {
        echo "\n🎉 验证成功！\n";
        echo "用户: {$verification['username']}\n";
        echo "角色: {$verification['role_name']} ({$verification['role_code']})\n";
    } else {
        echo "\n❌ 验证失败：用户角色关联未建立\n";
    }

} catch (Exception $e) {
    echo "❌ 错误: " . $e->getMessage() . "\n";
}
